
import { DbConnectionConfig } from "../../type/dbtype";
import { Connection } from "./connection";
import { mySqlDriver } from "./mysqldriver";
import { ThreadLocal } from "./threadlocal";
import { mysqlTransaction } from "./mysqltransaction";
// 修饰类的属性或方法，使其成为静态属性或静态方法。静态属性或方法不需要实例化对象即可访问，可以通过类名直接访问

class connectionManger {

    /**
     * 连接对象
     */
    static connection: Connection

    /**
     * 数据库
     */
    static mysqlconnection: mySqlDriver

    /**
     * 连接对象列表
     * 线程id  
     * connection  连接对象
     * transaction 事务对象
     */
    static connectionMap: Map<number, { connection?: Connection, transaction?: mysqlTransaction }> = new Map()

    /**
     * 
     * @param cfg 配置
     */
    static init(cfg: DbConnectionConfig) {
        this.mysqlconnection = new mySqlDriver(cfg)
    }

    /**
     * 连接管理器创建连接对象，获取实际连接
     */
    static async createConnection(): Promise<Connection> {
        let id = ThreadLocal.getThreadId()
        if (!id) {
            id = ThreadLocal.newThreadId()
        }
        if (this.connectionMap.has(id) && this.connectionMap.get(id).connection) {
            // id = ThreadLocal.newThreadId()
            return this.connectionMap.get(id).connection
        }
        //连接列表里没有该线程
        if (!this.connectionMap.has(id)) {
            this.connectionMap.set(id, {})
            //新建连接对象 存入连接列表
            let connection = new Connection(await this.mysqlconnection.getConnection())
            this.connectionMap.get(id).connection = connection
            return connection
        }
    }

    /**
     * 创建事务
     * @param connection 连接对象
     * @returns 
     */
    static getTransaction(connection: Connection): mysqlTransaction {
        let id = ThreadLocal.getThreadId()
        if (this.connectionMap.get(id).transaction) {
            return this.connectionMap.get(id).transaction
        }
        else {
            //新建事务对象
            const tx = Reflect.construct(mysqlTransaction, [connection])
            this.connectionMap.get(id).transaction = tx
            return tx
        }

    }

    /**
     * shanchu shiwu
     */
    static deleteTransaction() {
        let id = ThreadLocal.getThreadId()
        if (this.connectionMap.has(id)) {
            delete this.connectionMap.get(id).transaction
        }
    }

    /**
    * 连接管理器 关闭连接
    */
    static async close(connection: Connection) {
        return await this.mysqlconnection.closeConnection(connection)
    }

    /**
     * 删除连接
     */
    static async release() {
        let id = ThreadLocal.getThreadId()
        if (this.connectionMap.has(id)) {
            this.connectionMap.delete(id)
        }
    }
}

export { connectionManger }






